import time
from selenium.webdriver.common.by import By
from common.Utils import BlogDriver


class BlogEdit:
    def __init__(self):
        self.url = "http://8.137.19.140:9090/blog_edit.html"
        self.driver = BlogDriver.driver
        self.driver.get(self.url)
        time.sleep(1)  # 等待页面加载

    def EditSucTestByLogin(self):
        """成功编辑博客测试"""
        try:
            # 生成唯一标题
            timestamp = time.strftime("%Y%m%d%H%M%S")
            blog_title = f"自动化测试创建_{timestamp}"

            # 输入标题
            title_field = self.driver.find_element(By.CSS_SELECTOR, "#title")
            title_field.clear()
            title_field.send_keys(blog_title)

            # 处理富文本编辑器（简单示例）
            # 实际项目中可能需要切换frame等操作
            self.driver.switch_to.frame("ueditor_0")
            content_field = self.driver.find_element(By.CSS_SELECTOR, "body")
            content_field.clear()
            content_field.send_keys(f"这是自动化测试创建的博客内容，时间戳: {timestamp}")
            self.driver.switch_to.default_content()

            # 点击发布按钮
            self.driver.find_element(By.CSS_SELECTOR, "#submit").click()
            time.sleep(2)  # 等待发布完成

            # 验证发布成功
            actual_title = self.driver.find_element(
                By.CSS_SELECTOR,
                "body > div.container > div.right > div:nth-child(1) > div.title"
            ).text

            print(f"期望标题: {blog_title}, 实际标题: {actual_title}")
            assert blog_title == actual_title

            BlogDriver.getScreeShot()
            return True
        except Exception as e:
            print("博客编辑测试失败:", str(e))
            BlogDriver.getScreeShot()
            return False